$psake.use_exit_on_error = $true
properties {
    $currentDir = resolve-path .
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value
    $baseDir = $psake.build_script_dir
    $versionTag = "0"
    $versionTag = git describe --abbrev=0 --tags
    if(!$versionTag){$versionTag = "0"}
    $version = $versionTag + "."
    $version += (git log $($version + '..') --pretty=oneline | measure-object).Count
    $nugetExe = "$baseDir\tools\nuget"
    $pesterDir = ([array](dir "$baseDir\tools\packages\pester.*"))[-1]
}

Task default -depends Build
Task Build -depends Test, Package
Task Package -depends Version-Module, Pack-Nuget, Unversion-Module
Task Release -depends Build, Push-Nuget, Push-Codeplex

Task Test {
    CD "$baseDir"
    exec {."$pesterDir\tools\bin\Pester.bat" ./Tests}
    CD $currentDir
}

Task Version-Module{
    $v = git describe --abbrev=0 --tags
    $changeset=(git log -1 $($v + '..') --pretty=format:%H)
    (Get-Content "$baseDir\module\BigGit.psm1") | % {$_ -replace "\`$version\`$", "$version" } | % {$_ -replace "\`$sha\`$", "$changeset" } | Set-Content "$baseDir\module\BigGit.psm1"
}

Task Unversion-Module{
    $v = git describe --abbrev=0 --tags
    if(!$v){$v="0"}
    $changeset=(git log -1 $($v + '..') --pretty=format:%H)
    (Get-Content "$baseDir\module\BigGit.psm1") | % {$_ -replace "$version", "`$version`$" } | % {$_ -replace "$changeset", "`$sha`$" } | Set-Content "$baseDir\module\BigGit.psm1"
}

Task Pack-Nuget {
    if (Test-Path "$baseDir\build") {
      Remove-Item "$baseDir\build" -Recurse -Force
    }

    mkdir "$baseDir\build"
    exec { .$nugetExe pack "$baseDir\BigGit.nuspec" -OutputDirectory "$baseDir\build" -NoPackageAnalysis -version "$version" }
}

Task Push-Nuget {
    $pkg = Get-Item -path $baseDir\build\BigGit.1.*.*.nupkg
    exec { cpush $pkg.FullName }
}

Task Push-Codeplex {
    Add-Type -Path "$basedir\tools\CodePlexClientAPI\CodePlex.WebServices.Client.dll"
     $releaseService=New-Object CodePlex.WebServices.Client.ReleaseService
     $releaseService.Credentials = Get-Credential -Message "Codeplex credentials" -username "mwrock"
     $releaseService.CreateARelease("biggit","BigGit $version","",[DateTime]::Now,[CodePlex.WebServices.Client.ReleaseStatus]::Beta, $true, $true)
}
